package com.dsunsoft.rtu.common.util;

import com.dsunsoft.rtu.common.constant.CommonConstants;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * HttpUtils
 */
public class WebUtils {

    /**
     * 获取url参数为map
     */
    public static Map<String, String> getQueryMap(HttpServletRequest request) throws IOException {
        Map<String, String> queryMap = new HashMap<String, String>();
        String queryString = request.getQueryString();
        String[] params = queryString.split("&");
        for (int i = 0; i < params.length; i++) {
            String[] kv = params[i].split("=");
            if (kv.length == 2) {
                String key = URLDecoder.decode(kv[0], CommonConstants.UTF_8);
                String value = URLDecoder.decode(kv[1], CommonConstants.UTF_8);
                queryMap.put(key, value);
            } else if (kv.length == 1) { // 参数值为空
                String key = URLDecoder.decode(kv[0], CommonConstants.UTF_8);
                queryMap.put(key, "");
            }
        }
        return queryMap;
    }

    /**
     * 获取表单参数为map
     */
    public static Map<String, String> getFormMap(HttpServletRequest request) {
        Map<String, String> formMap = new HashMap<String, String>();
        Set<?> keys = request.getParameterMap().keySet();
        for (Object tmp : keys) {
            String key = String.valueOf(tmp);
            String value = request.getParameter(key);
            if (StringUtils.isEmpty(value)) {
                formMap.put(key, "");
            } else {
                formMap.put(key, value);
            }
        }
        return formMap;
    }

    /**
     * 读取http InputStream
     */
    public static String getStreamAsString(HttpServletRequest request) throws IOException {
        InputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
            Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            StringBuilder response = new StringBuilder();
            final char[] buff = new char[1024];
            int read = 0;
            while ((read = reader.read(buff)) > 0) {
                response.append(buff, 0, read);
            }
            return response.toString();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

}
